package ma.xin.shi.common;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;

public class MultiSelectDialog {

    public static List<String> show(Shell parentShell, String title, String[] availableOptions, String[] initialSelections) {
        Shell shell = new Shell(parentShell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
        shell.setText(title);
        shell.setLayout(new GridLayout());

        CheckboxTableViewer viewer = CheckboxTableViewer.newCheckList(shell, SWT.BORDER);
        viewer.setContentProvider(ArrayContentProvider.getInstance());
        viewer.setLabelProvider(new LabelProvider());
        viewer.setInput(availableOptions);

        List<String> selectedItems = new ArrayList<>(List.of(initialSelections));

        for (String option : availableOptions) {
            viewer.setChecked(option, selectedItems.contains(option));
        }

        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
        gd.widthHint = 300;
        gd.heightHint = 200;
        viewer.getControl().setLayoutData(gd);

        Composite buttonComposite = new Composite(shell, SWT.NONE);
        buttonComposite.setLayout(new RowLayout(SWT.HORIZONTAL));
        buttonComposite.setLayoutData(new GridData(SWT.END, SWT.CENTER, true, false));

        Button okButton = new Button(buttonComposite, SWT.PUSH);
        okButton.setText("确定");

        Button cancelButton = new Button(buttonComposite, SWT.PUSH);
        cancelButton.setText("取消");

        final List<String> result = selectedItems;

        viewer.addCheckStateListener(event -> {
            if (event.getChecked()) {
                result.add((String) event.getElement());
            } else {
                result.remove(event.getElement());
            }
        });

        okButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.close();
            }
        });

        cancelButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                result.clear(); // 取消时返回空
                shell.close();
            }
        });

        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!parentShell.getDisplay().readAndDispatch()) {
                parentShell.getDisplay().sleep();
            }
        }

        return result;
    }
}
